//priority 10000
function CustomMachineGuiBase(machineId) {
    this.id = machineId
}

var guiCallback = {}
CustomMachineGuiBase.prototype.tick = function (/** @type {(handler: ContainerGuiTickEvent) => void} */callback) {
    guiCallback[this.id] = callback
}
var guiCallback_init = {}
CustomMachineGuiBase.prototype.init = function (/** @type {(handler: ContainerGuiTickEvent) => void} */callback) {
    guiCallback_init[this.id] = callback
}

/**@type ContainerGuiTickEvent*/
var CurrentContainerGuiTickEvent
var CurrentMachineFunc
ClientEvents.tick(event => {
    if (CurrentMachineFunc) {
        CurrentMachineFunc(CurrentContainerGuiTickEvent)
        var currentScreen = Client.getCurrentScreen()
        if (currentScreen == null) {
            CurrentMachineFunc = null
        }
    }

})


function ContainerGuiTickEvent(/**@type Internal.Player*/player, /**@type BlockPos*/blockpos) {
    this.player = player
    this.blockpos = blockpos
}

NetworkEvents.dataReceived("CustomMachineContainerOpen", event => {
    var { player, data } = event
    var machineId = data.getString("type")
    var pos = data.get("pos")
    CurrentContainerGuiTickEvent = new ContainerGuiTickEvent(player, new BlockPos(pos.x, pos.y, pos.z))
    CurrentMachineFunc = functionFinder(machineId, guiCallback)
    var CurrentMachineFuncInit = functionFinder(machineId, guiCallback_init)
    if (CurrentMachineFuncInit) {
        CurrentMachineFuncInit(CurrentContainerGuiTickEvent)
    }
})


NetworkEvents.dataReceived("CustomMachineContainerClose", event => {
    CurrentMachineFunc = null
    GUI.forEach(/** @type {(handler: BaseGui) => void} */ obj => {
        obj.update({ visible: false })
    });
})

function functionFinder(name, table) {
    for (const funcName in table) {
        if (name == funcName) {
            return table[name]
        }
    }
    return null
}

function getCustomMachineState(/**@type Internal.Player*/player, /**@type BlockPos*/blockpos, stateName) {
    player.sendData("getCustomMachineState", { "stateName": stateName, "blockpos": { x: blockpos.x, y: blockpos.y, z: blockpos.z } })
}